﻿using Liang.DataBase.DAL;
using Liang.DataBase.IBLL;
using Liang.DataBase.IDAL;
using Liang.DataBase.Model;
using Liang.DataBase.Model.Entity;
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Data.Entity;
using Liang.Model;

namespace Liang.DataBase.BLL
{
    /// <summary>
    /// 业务逻辑基类
    /// </summary>
    /// <typeparam name="T">实体对象类型</typeparam>
    /// <typeparam name="U">数据层操作接口</typeparam>
    public abstract class BaseBLL<T, U> : IBaseBLL<T> 
        where T : class
        where U : IBaseDAL<T>
    {

        private static readonly object syncRoot = new Object();

        protected U baseDAL { get; set; }

        /// <summary>
        /// 实例化一个控制器，实现对象注入
        /// </summary>
        IUnityContainer container { get; set; }

        /// <summary>
        /// 默认构造函数。
        /// 默认获取缓存的容器，如果没有则创建容器，并注册所需的接口实现。
        /// </summary>
        public BaseBLL()
        {
            lock (syncRoot)
            {
                container = DALFactory.Instance.Container;
                if (container == null)
                {
                    throw new ArgumentNullException("container", "container没有初始化");
                }
            }

            baseDAL = container.Resolve<U>();
        }

        public bool Insert(T t)
        {
            return baseDAL.Insert(t);
        }

        public bool Delete(object id)
        {
            return baseDAL.Delete(id);
        }

        public bool Delete(T t)
        {
            return baseDAL.Delete(t);
        }

        public bool Update(T t, object key)
        {
            return baseDAL.Update(t,key);
        }

        public T FindByID(object id)
        {
            return baseDAL.FindByID(id);
        }

        public T FindSingle(Expression<Func<T, bool>> match)
        {
            return baseDAL.FindSingle(match);
        }

        public IList<T> FindAll()
        {
            return baseDAL.FindAll();
        }

        public IList<T> FindAll(Expression<Func<T, bool>> match)
        {
            return baseDAL.FindAll(match);
        }

        public IList<T> FindWithOrderby(Expression<Func<T, bool>> match, string propertyName, bool isDesc = true)
        {
            return baseDAL.FindWithOrderby(match, propertyName, isDesc);
        }

        public IList<T> FindWithPagerAndOrderby(Expression<Func<T, bool>> match, ref PageInfo info, string propertyName, bool isDesc = true)
        {
            return baseDAL.FindWithPagerAndOrderby(match, ref info, propertyName,isDesc);
        }
    }
}
